package cn.zhangfusheng.elasticsearch.model.analysis;

import cn.zhangfusheng.elasticsearch.constant.enumeration.SearchKeyword;
import cn.zhangfusheng.elasticsearch.exception.GlobalSystemException;
import cn.zhangfusheng.elasticsearch.model.es.EsRange;
import cn.zhangfusheng.elasticsearch.model.es.GeoDistance;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.Collection;

/**
 * 查询关键字的解析
 * @author fusheng.zhang
 * @date 2022-05-11 16:05:56
 */
public class AnalysisSearchKeyword {

    public QueryBuilder builder(String k, Object v, SearchKeyword searchKeyword) {
        switch (searchKeyword) {
            case MATCH_ALL: return QueryBuilders.matchAllQuery();
            case MATCH: return QueryBuilders.matchQuery(k, v);
            case MULTI_MATCH: return QueryBuilders.multiMatchQuery(k, String.valueOf(v));
            case MATCH_PHRASE: return QueryBuilders.matchPhraseQuery(k, v);
            case TERM: return QueryBuilders.termQuery(k, v);
            case FUZZY: return QueryBuilders.fuzzyQuery(k, v);
            case PREFIX: return QueryBuilders.prefixQuery(k, String.valueOf(v));
            case RANGE:
                if (v instanceof EsRange) {
                    return ((EsRange) v).builder(QueryBuilders.rangeQuery(k));
                }
                throw new GlobalSystemException("range query params muster instanceof {}", EsRange.class.getName());
            case WILDCARD: return QueryBuilders.wildcardQuery(k, String.valueOf(v));
            case REGEXP: return QueryBuilders.regexpQuery(k, String.valueOf(v));
            case SPAN_TERM: return QueryBuilders.spanTermQuery(k, String.valueOf(v));
            case TERMS:
                if (v instanceof Collection) {
                    return QueryBuilders.termsQuery(k, (Collection<?>) v);
                }
                throw new GlobalSystemException("terms value master instanceof Collection");
            case GEO_DISTANCE:
                if (v instanceof GeoDistance) {
                    GeoDistance geoDistance = (GeoDistance) v;
                    if (StringUtils.isBlank(geoDistance.getDistance())) return null;
                    return QueryBuilders.geoDistanceQuery(k)
                            .point(geoDistance.getLat(), geoDistance.getLon())
                            .distance(geoDistance.getDistance(), geoDistance.getUnit())
                            .geoDistance(geoDistance.getGeoDistance());
                }
                throw new GlobalSystemException("geoDistanceQuery value master instanceof {}", GeoDistance.class.getName());
            case GEO_BOUNDING_BOX: return QueryBuilders.geoBoundingBoxQuery(k);
            case EXISTS: return QueryBuilders.existsQuery(k);
            default: throw new GlobalSystemException("不支持的搜索关键字");
        }
    }
}
